#include "configeditor.h"
#include <QFileInfo>
#include <QDebug>
#include <QJsonValueRef>

ConfigEditor::ConfigEditor()
{

}

//Set
void ConfigEditor::set_root_config_obj(QJsonObject obj)
{
    root_config_obj_=obj;
}

void ConfigEditor::setValue(QStringList path, QVariant value)
{

    QList<QJsonObject> mid_obj_list;
    qDebug()<<"before revise"<<getValue(path);
    QJsonObject current_obj=root_config_obj_;

    int num=path.size();

    //
    for (int i=0; i<num-1; ++i) {
        QString key=path.at(i);
        if(current_obj.contains(key)){
            if(current_obj[key].isObject()){
                current_obj=current_obj[key].toObject();
                mid_obj_list.push_back(current_obj);
            }
            else {
                qDebug()<<"key error"<<key;
                return;
            }
        }
        else {
            return;
        }
    }

    if(current_obj.contains(path.back()) ){
        mid_obj_list.back()[path.back()]=QJsonValue::fromVariant(value);
    }
    else{
        qDebug()<<"last key error:"<<path.back();
        return;
    }

    for(int i=num-3; i>-1; --i){
        mid_obj_list[i][path[i+1]]=mid_obj_list[i+1];
    }
    root_config_obj_[path[0]]=mid_obj_list[0];

    qDebug()<<"after revise"<<getValue(path);
}


//
QVariant ConfigEditor::getValue(QStringList path)
{
    QJsonObject current_obj=root_config_obj_;
    int num=path.size();
    for (int i=0; i<num-1; ++i) {
        QString key=path.at(i);
        if(current_obj.contains(key)){
            if(current_obj[key].isObject())
                current_obj=current_obj[key].toObject();
            else {
                qDebug()<<"key error"<<key;
                return QVariant();
            }
        }
        else {
            return QVariant();
        }
    }
    if(current_obj.contains(path.back()) ){
        return current_obj[path.back()].toVariant();
    }
}
